//
//  LoginAndRegisterVC.m
//  SHShopping
//
//  Created by 坤鼎 on 2019/9/5.
//  Copyright © 2019 kunding. All rights reserved.
//

#import "LoginAndRegisterVC.h"
#import "SMSCodeVC.h"
#import "RefreshLineView.h"

@interface LoginAndRegisterVC () <UITextFieldDelegate>

@property (nonatomic, strong) BaseButton *btnLogo;

@property (nonatomic, strong) UITextField *tf;

@property (nonatomic, strong) UIButton *btnOK;
//@property (nonatomic, strong) RefreshLineView *refreshLineView;

/**
 UITextField 字符最大长度
 */
@property (nonatomic, assign) NSInteger textlength;

@property (nonatomic, assign) NSInteger insertIndex;//定义全局变量

@end

@implementation LoginAndRegisterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.insertIndex = 0;
    self.textlength = 11 + 2;
    [self initView];
}

- (void)backToHome {
    if (self.pushType == 1) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)initView {
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:ImageNamed(@"enter") style:UIBarButtonItemStyleDone target:self action:@selector(backToHome)];
    self.navigationItem.leftItemsSupplementBackButton = YES;
    
    self.btnLogo = [[BaseButton alloc] initWithFrame:CGRectMake(31, 53, 64, 64)];
    UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(12 + GetViewXW(self.btnLogo), 66, 200, 39)];
    self.tf = [[UITextField alloc] initWithFrame:CGRectMake(31, GetViewYH(lbTitle) + 102, SCREEN_WIDTH - 62, 40)];
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(31, GetViewYH(self.tf), SCREEN_WIDTH - 62, 0.5)];
    self.btnOK = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 77) / 2, GetViewYH(lineView) + 64, 77, 77)];
    UIButton *btnBottom = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 44 - 32 - kNavBarAndStatusBarHeight, SCREEN_WIDTH, 44)];
    
    [self.view addSubview:self.btnLogo];
    [self.view addSubview:lbTitle];
    [self.view addSubview:self.tf];
    [self.view addSubview:lineView];
    [self.view addSubview:self.btnOK];
    [self.view addSubview:btnBottom];
    
    [self.btnLogo setImage:ImageNamed(@"启动页png") forState:UIControlStateNormal];
    lbTitle.text = @"账号注册";
    lbTitle.font = FONT_BOLD(28);
    
    UIButton *leftView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70, 28)];
    [leftView setTitle:@"+86 ˇ" forState:UIControlStateNormal];
    leftView.titleLabel.font = FONT(20);
    [leftView setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.tf.leftViewMode = UITextFieldViewModeAlways;
    self.tf.leftView = leftView;
    NSString *holderText = @"请输入您的手机号";
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:holderText];
    [placeholder addAttribute:NSForegroundColorAttributeName
                  value:UIColorFromRGB(0x999999)
                  range:NSMakeRange(0, holderText.length)];
    [placeholder addAttribute:NSFontAttributeName
                  value:FONT(19)
                  range:NSMakeRange(0, holderText.length)];
    self.tf.attributedPlaceholder = placeholder;
    self.tf.delegate = self;
    self.tf.font = FONT_BOLD(24);
    self.tf.keyboardType = UIKeyboardTypeNumberPad;
    [self.tf addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    lineView.backgroundColor = UIColorFromRGB(0xDDDDDD);
    
    [self.btnOK setImage:ImageNamed(@"login_Next_N") forState:UIControlStateNormal];
    self.btnOK.userInteractionEnabled = NO;
    [self.btnOK addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    
    NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:@"登录即代表阅读并同意服务协议"];
    [attriStr addAttribute:NSFontAttributeName value:FONT_BOLD(13) range:NSMakeRange(10, 4)];
    [btnBottom setAttributedTitle:attriStr forState:UIControlStateNormal];
    btnBottom.titleLabel.font = FONT(12);
    [btnBottom addTarget:self action:@selector(actionAgreement) forControlEvents:UIControlEventTouchUpInside];
    btnBottom.hidden = YES;
}

- (void)actionAgreement {
    WKWebViewController *vc = [[WKWebViewController alloc] initWithURLString:@"https://www.baidu.com/duty/"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)loginAction {
//    self.refreshLineView.hidden = NO;
//    [self.refreshLineView beginRefresh];
 
    if (self.tf.text.length != 13) {
        [SXLoadingView showAlertHUD:@"手机号码长度错误" duration:SXLoadingTime];
        return;
    }
#pragma mark - 2019年手机号码正则表达式
    NSString *MOBILE = @"^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[1,3,5,8,9])\\d{8}$";
    
    NSPredicate *pred_mobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    NSString *phoneNum = [self.tf.text stringByReplacingOccurrencesOfString:@" "withString:@""];
    
    BOOL isMatch = [pred_mobile evaluateWithObject:phoneNum];
    
    if (!isMatch) {
        [SXLoadingView showAlertHUD:@"手机号码格式错误" duration:SXLoadingTime];
        return;
    }
    
    {
//        NSDictionary *par = @{@"mobile":phoneNum};
//        [SXLoadingView showProgressHUD:nil];
//        [PPNetworkHelper POST:URL_smsSend parameters:par success:^(id responseObject) {
//        //        [self.refreshLineView endRefresh];
//            SMSCodeVC *vc = [[SMSCodeVC alloc] init];
//            vc.phoneNum = phoneNum;
//            vc.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:vc animated:YES];
//
//            if ([responseObject[@"success"] boolValue] == YES) {
//                [vc openCountdown];
//            } else {
//                [SXLoadingView showAlertHUD:responseObject[@"retMsg"] duration:SXLoadingErrorTime];
//            }
//        } failure:^(NSError *error) {
//            //        [self.refreshLineView endRefresh];
//            [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
//        }];
    }
    
    {
        SMSCodeVC *vc = [[SMSCodeVC alloc] init];
        vc.phoneNum = phoneNum;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}





#pragma mark - textField代理

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    [self.refreshLineView endRefresh];
    
#pragma mark - 手机号指定位置添加空格 如 188 8888 8888
    if (textField == self.tf) {
        if (textField.text.length > self.insertIndex) {
            if (textField.text.length == 4 || textField.text.length == 9) {//输入
                NSMutableString * str = [[NSMutableString alloc ] initWithString:textField.text];
                [str insertString:@" " atIndex:(textField.text.length - 1)];
                textField.text = str;
            }
            if (textField.text.length >= self.textlength) {//输入完成
                [textField resignFirstResponder];
            }
            self.insertIndex = textField.text.length;
            
        } else if (textField.text.length < self.insertIndex) {//删除
            if (textField.text.length == 4 || textField.text.length == 9) {
                textField.text = [NSString stringWithFormat:@"%@",textField.text];
                textField.text = [textField.text substringToIndex:(textField.text.length - 1)];
            }
            self.insertIndex = textField.text.length;
        }
    }

    NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
    
    if (proposedNewLength >= self.textlength) {
        [self.btnOK setImage:ImageNamed(@"login_Next_Y") forState:UIControlStateNormal];
        self.btnOK.userInteractionEnabled = YES;
    } else {
        [self.btnOK setImage:ImageNamed(@"login_Next_N") forState:UIControlStateNormal];
        self.btnOK.userInteractionEnabled = NO;
    }
    
    if (proposedNewLength > self.textlength) {
        return NO;//限制长度
    } else {
        return YES;
    }
}

- (void)textFieldEditingChanged:(UITextField *)textField {
//    if (textField == self.tf) {
//        if (textField.text.length > self.i) {
//            if (textField.text.length == 4 || textField.text.length == 9 ) {//输入
//                NSMutableString * str = [[NSMutableString alloc ] initWithString:textField.text];
//                [str insertString:@" " atIndex:(textField.text.length-1)];
//                textField.text = str;
//            }
//            if (textField.text.length >= 13 ) {//输入完成
//                textField.text = [textField.text substringToIndex:13];
//                [textField resignFirstResponder];
//            }
//            self.i = textField.text.length;
//
//        } else if (textField.text.length < self.i) {//删除
//            if (textField.text.length == 4 || textField.text.length == 9) {
//                textField.text = [NSString stringWithFormat:@"%@",textField.text];
//                textField.text = [textField.text substringToIndex:(textField.text.length-1)];
//            }
//            self.i = textField.text.length;
//        }
//    }
}

@end
